import { defineComponent, nextTick, ref, Fragment,onMounted,watch, } from "vue";
import { NIcon, NDropdown, useMessage, } from "naive-ui"
import { CloseOutlined } from "@vicons/antd"
import {storeToRefs} from "pinia"
import {useMyRouter} from "@/store/moduls/usemyroute"
import {useRouter,useRoute,} from "vue-router";
interface OptionItem {
    key: string | number,
    label: string,
    children?: Array<OptionItem>,
}

interface RouteItem {
    key: string | number,
    label: string,
    children?: Array<RouteItem>,
    name:string,
}

export default defineComponent({
    name: "Taglist",
    props:{
        callInitFunc:{
            type:Function,
        }
    },
    setup(props,) {
        const router = useRouter();
        const route = useRoute();
        const message = useMessage()
        const usemyrouter:any = useMyRouter()
        const {routelist:panels} = storeToRefs(usemyrouter)
        // 被右键点击的标签
        const selectedTab = ref(undefined)
        // 左键点击标签
        const handleClick = (index: number) => {
            const item = panels.value[index]
            router.push({name:item.name})
        }
        // 关闭标签
        const handleClose = (index: number) => {
            const name:string = panels.value[index].name
            usemyrouter.yichu([name])
        }
        // 右键点击
        const handleContextmenu = (event: MouseEvent, index: number) => {
            event.preventDefault();
            showDropdown.value = false
            selectItem.value = panels.value[index]
            nextTick(() => {
                showDropdown.value = true
                x.value = event.clientX
                y.value = event.clientY
            })
        }

        // 右键菜单
        const selectItem = ref<null | RouteItem>(null)
        const options = ref<Array<OptionItem>>([
            { label: "刷新", key: "refresh" },
            { label: "关闭", key: "close" },
            { label: "全部关闭", key: "closeall" },
            { label: "关闭其他", key: "closeother" },
            { label: "关闭左侧", key: "closeleft" },
            { label: "关闭右侧", key: "closeright" },
        ])
        const x = ref(0)
        const y = ref(0)
        const showDropdown = ref(false)
        const onClickoutside = () => {
            showDropdown.value = false
        }
        const handleSelect = (key: string | number) => {
            switch (key) {
                case "refresh":
                    message.success("refresh")
                    props.callInitFunc!(selectItem.value!.name)
                    break;
                case "close":
                    message.success("close")
                    usemyrouter.yichu([selectItem.value!.name])
                    break;
                case "closeall":
                    message.success("closeall")
                    usemyrouter.qingkong()
                    break;
                case "closeother":
                    message.success("closeother")
                    break;
                case "closeleft":
                    message.success("closeleft")
                    break;
                case "closeright":
                    message.success("closeright")
                    break;
            }
            onClickoutside()
            selectItem.value = null
        }
        // 存储所有的标签对象
        const tagsVnode = ref<{[key:string]:any}>({})
        const getRef = (el:any,name:string)=>{
            console.log("组件注册：",name)
            tagsVnode.value[name] = el
        }

        /*********************************************************************************
         挂载完成生命周期，顶部tab栏的左右滑动监听
         *********************************************************************************/
        onMounted(() => {
            const huadongref: HTMLElement | null = document.getElementById('huadongref')
            //判断浏览器
            let isIE: any = navigator.userAgent.match(/MSIE (\d)/i)
            isIE = isIE ? isIE[1] : undefined
            let isFF = /FireFox/i.test(navigator.userAgent)

            if (isIE < 9)
                //传统浏览器使用MouseWheel事件
                huadongref?.attachEvent('onmousewheel', function(e: any) {
                    console.log('IE9一下的浏览器触发滚动')
                    //计算鼠标滚轮滚动的距离
                    //一格3行，每行40像素
                    let v = e.wheelDelta / 2
                    huadongref.scrollLeft += v
                    //阻止浏览器默认方法
                    return false
                })
            else if (!isFF)
                //除火狐外的现代浏览器也使用MouseWheel事件
                huadongref?.addEventListener(
                    'mousewheel',
                    function(e: any) {
                        console.log('除火狐以外的浏览器触发滚动')
                        //计算鼠标滚轮滚动的距离
                        let v = -e.wheelDelta / 2
                        huadongref.scrollLeft += v
                        //阻止浏览器默认方法
                        e.preventDefault()
                    },
                    false,
                )
            //火狐使用DOMMouseScroll事件
            else
                huadongref?.addEventListener(
                    'DOMMouseScroll',
                    function(e: any) {
                        console.log('火狐浏览器触发滚动')
                        //计算鼠标滚轮滚动的距离
                        //一格是3行，但是要注意，这里和像素不同的是它是负值
                        huadongref.scrollLeft += e.detail * 20
                        //阻止浏览器默认方法
                        e.preventDefault()
                    },
                    false,
                )
        })
        /*********************************************************************************
         监听区域，在route改变的时候，让当前激活的标签露出来
         *********************************************************************************/
        watch(route,()=>{
            nextTick(()=>{
                console.log("*************************************路由改变了，需要滑动标签**********************************************")
                const zujian = tagsVnode.value[route.name as string]
                console.log(zujian,"找到的组件是什么啊")
                // 如果没找到标签，就结束
                if(!zujian)return
                const offleft = zujian.offsetLeft
                const huadongref: HTMLElement | null = document.getElementById('huadongref')
                // 如果没找到元素，就结束
                if(!huadongref)return
                if (offleft > (huadongref!.scrollLeft + huadongref!.offsetWidth)) {
                    huadongref!.scrollLeft = offleft + 200
                } else if (huadongref!.scrollLeft > offleft) {
                    huadongref!.scrollLeft = offleft
                }
            })
        })
        return () => (
            <Fragment>
                <div id="huadongref" class="w-full h-30px overflow-x-hidden overflow-y-hidden flex items-center">
                    {() => panels.value.map((item: any, index: number) => {
                        return <div ref={(el)=>getRef(el,item.name)} class={[ item.name===route.name?"bg-blue-400 text-white":"bg-gray-200 text-black", " w-200px h-40px juzhong1 cursor-pointer border-r border-t border-b border-gray-400 flex-shrink-0"]} onContextmenu={(event) => handleContextmenu(event, index)}>
                            <div class="flex-1 h-40px juzhong1 truncate text-center hover:text-red-400" onClick={() => handleClick(index)}>
                                <span>{item.name}</span>
                            </div>
                            <NIcon class="h-40 mx-4px juzhong1 hover:text-red-400" onClick={() => handleClose(index)}>
                                <CloseOutlined class="w-16 h-16" />
                            </NIcon>
                        </div>
                    })}
                </div>
                <NDropdown
                    placement={"bottom-start"}
                    trigger={"manual"}
                    x={x.value}
                    y={y.value}
                    options={options.value}
                    show={showDropdown.value}
                    onClickoutside={onClickoutside}
                    onSelect={handleSelect}
                />
            </Fragment>
        )
    },
})
